<?php

namespace App\Http\Controllers\Api\Orders;

use App\Http\Controllers\Controller;
use App\Http\Resources\Task\TrainSnapTaskInfoResource;
use App\Models\Task\SnapTasks\Repositories\Interfaces\SnapTaskRepositoryInterface;
use App\Models\Task\SnapTasks\SnapTask;
use App\Models\Train\TrainOrders\Repositories\Interfaces\TrainOrdersRepositoryInterface;
use App\Trip\Orders\BookOrders\BookOrdersManager;
use App\Trip\Train\Order\Impl\SnapTaskLowLevel\SnapTaskLowLevelImpl;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;

class SnapTaskController extends Controller
{
    private SnapTaskRepositoryInterface    $snapTaskRepository;
    private TrainOrdersRepositoryInterface $trainOrdersRepository;

    public function __construct(
        SnapTaskRepositoryInterface    $snapTaskRepository,
        TrainOrdersRepositoryInterface $trainOrdersRepository
    )
    {
        $this->snapTaskRepository    = $snapTaskRepository;
        $this->trainOrdersRepository = $trainOrdersRepository;
    }

    /**
     * 任务详情
     *
     * @param Request $request
     *
     * @return
     */
    public function task_info(Request $request)
    {
        $task_info = null;
        if ($request->input('task_id')) {
            $task_info = $this->snapTaskRepository->findOneByTaskId($request->input('task_id'));
        } elseif ($request->input('trip_id')) {
            $task_info = $this->snapTaskRepository->findOneByTripId($request->input('trip_id'));
        } elseif ($request->input('order_sn')) {
            $order_info = $this->trainOrdersRepository->getOrderInfo($request->input('order_sn'));
            $task_info  = $order_info?->getTaskId() ? $this->snapTaskRepository->findOneByTaskId($order_info->getTaskId()) : null;
        }

        if (!$task_info) {
            return $this->error(404, "抢票任务不存在");
        }

        if (Gate::denies('order-task-access', $task_info)) {
            return $this->error(404, "抢票任务不存在");
        }
        return $this->success("", ['task_info' => new TrainSnapTaskInfoResource($this->snapTaskRepository->getTaskShowInfo($task_info))]);
    }

    /**
     * 编辑抢票任务
     *
     * @throws Exception
     */
    public function edit_task(Request $request)
    {

        $order_manager   = new BookOrdersManager($request->only('task_id', 'snap_level', 'order'));
        $task_order_data = $order_manager->task_edit();
        $task_order      = $task_order_data['order_info'];
        $task_info       = $task_order->snap_task_info();
        if (Gate::denies('order-task-access', $task_info)) {
            return $this->error(404, "抢票任务不存在");
        }
        return $this->success("", [
            'task_info' => new TrainSnapTaskInfoResource($this->snapTaskRepository->getTaskShowInfo($task_info)),
            'pay_info'  => $task_order_data['pay_info'],
        ]);
    }

    /**
     *     取消任务
     *
     * @param Request $request
     *
     */
    public function cancel(Request $request)
    {
        $task_id  = $request->input('task_id', '');
        $order_sn = $request->input('order_sn', '');
        if (!($task_id) && !($order_sn)) {
            return $this->error(1, "参数错误");
        }

        if (!$task_id) {
            $order_info = $this->trainOrdersRepository->getOrderInfo($order_sn);
            $task_id    = $order_info?->getTaskId() ?: '';
        }


        $task_info = $this->snapTaskRepository->findOneByTaskId($task_id);
        if (Gate::denies('order-task-access', $task_info)) {
            return $this->error(404, "抢票任务不存在");
        }
        $this->snapTaskRepository->cancelTask($task_info);
        return $this->success('任务已取消');

    }

    /**
     * 修改 自动抢票状态
     *
     * @param Request $request
     *
     */
    public function auto_ticket_switch(Request $request)
    {
        $task_id   = $request->input('task_id');
        $state     = $request->input('auto_ticket');
        $task_info = $this->snapTaskRepository->findOneByTaskId($task_id);
        if (Gate::denies('order-task-access', $task_info)) {
            return $this->error(404, "抢票任务不存在");
        }

        if ($task_info->isPaidHighLevel()) {
            return $this->error(1, '为了保证抢票成功率，高速抢票默认自动出票，不可更改');
        }

        if (!$task_info->can_edit_switch()) {
            return $this->error(1, "抢票任务当前不可修改自动抢票");
        }


        if ($state == $task_info->getAutoTicketState()) {
            return $this->error(1, "您操作的太快了");
        }


        $this->snapTaskRepository->updateAutomaticTicketState($task_info, $state);
        return $this->success("修改成功");

    }

    /**
     * 低速 出票确认
     *
     * @param Request $request
     *
     * @throws Exception
     */
    public function ticket_confirm(Request $request)
    {
        $task_id   = $request->input('task_id');
        $task_info = $this->snapTaskRepository->findOneByTaskId($task_id);
        if (Gate::denies('order-task-access', $task_info)) {
            return $this->error(1, "抢票任务不存在");
        }

        // 刷到票后 更新 main_train
        // 用 main_train => 去下单
        if ($task_info->isPaidHighLevel()) {
            return $this->error(1, "您当前为高速抢票,无需手动确认出票");
        }

        if ($task_info->isAutoTicket()) {
            return $this->error(1, "您已开启自动出票无需手动确认出票");
        }

        if ($task_info->getSnapState() != SnapTask::SNAP_STATE_HAS_TICKET) {
            return $this->error(1, "已过期");
        }

        $low_level_snap = new SnapTaskLowLevelImpl($task_id, 'ticket');
        $current_trip   = $low_level_snap->trips()->getSnapTaskTripByIndex($low_level_snap->getCurrentTripIndex());
        $ticket_res     = $low_level_snap->ticket($current_trip);
        if (!$ticket_res) {
            return $this->error(1, $low_level_snap->getErrorMsg());
        }

        return $this->success('正在出票中');
    }
}
